package cn.linstudy.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author ljp
 * @Date 2021/12/14 10:47
 * @Description
 */
@Slf4j
public class FileUtils {

    public static final String TYPE_JPG = "jpg";
    public static final String TYPE_GIF = "gif";
    public static final String TYPE_PNG = "png";
    public static final String TYPE_BMP = "bmp";
    public static final String TYPE_UNKNOWN = "unknown";

    public static final String FORMAT_FILE_NAME = "%d.%s";

    private static byte[] b;

    /**
     * @param fis 文件输入流
     * @return
     * @description: 根据文件流判断图片类型
     */
    public static String getPicType(InputStream fis) {
        // 读取文件的前几个字节来判断图片格式
        b = new byte[4];
        try {
            fis.read(b, 0, b.length);
            String type = bytesToHexString(b).toUpperCase();
            if (type.contains("FFD8FF")) {
                return TYPE_JPG;
            } else if (type.contains("89504E47")) {
                return TYPE_PNG;
            } else if (type.contains("47494638")) {
                return TYPE_GIF;
            } else if (type.contains("424D")) {
                return TYPE_BMP;
            } else {
                return TYPE_PNG;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param src
     * @return
     * @description: byte数组转换成16进制字符串
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * @param dir
     * @description: 判断文件夹是否存在，不存在则创建
     */
    public static void isDirPathExist(File dir) {
        // 判断文件夹是否存在
        if (dir.isDirectory()) {
            log.debug(dir + "文件夹已存在");
        } else {
            log.debug(dir + "文件夹不存在");
            dir.mkdir();
            log.debug("创建文件夹" + dir);
        }
    }

    /**
     * @param File file
     * @description: 判断文件是否存在
     */
     public static Boolean isFileExists(File file) {
        if (file.exists()) {
            return true;
         } else {
            return false;
         }
    }

    /**
     * @description: 从服务器获得图片输入流InputStream, 并写到本地磁盘
     */
    public static String saveImageToDisk(InputStream inputStream, String diskPath) {
        // 根据文件流判断图片类型，此处不要关闭流,要不然下方获取不到输入流
        String picType = FileUtils.getPicType(inputStream);
        log.debug("图片格式为：" + picType);
        String fileName = String.format(FORMAT_FILE_NAME,System.currentTimeMillis(), picType);
        log.debug("图片名字为：" + fileName);
        byte[] data = new byte[1024];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        try {
            File dirFile = new File(diskPath);
            log.info("本次图片【{}】保存路径为【{}】", fileName, diskPath);
            // 判断文件夹是否存在，不存在则创建
            mkdirs(dirFile);
            fileOutputStream = new FileOutputStream(new File(dirFile, fileName));
            // 首先写入判断图片格式的前几个字节
            fileOutputStream.write(b, 0, b.length);
            while ((len = inputStream.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);
            }
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        log.debug("写到本地磁盘完成：" + fileName);
        return fileName;
    }

    /**
     * @return
     * @description: 从服务器获得一个输入流(本例是指从服务器获得一个image输入流)
     */
    public static InputStream getInputStream(String urlPath) {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(urlPath);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置网络连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置应用程序要从网络连接读取数据
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                // 从服务器返回一个输入流
                inputStream = httpURLConnection.getInputStream();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 保存网络地址图片到服务器
     *
     * @param url
     * @param savePath 需要保存的路径
     * @return
     */
    public static String saveImgByUrl(String url, String savePath) {
        InputStream inputStream = getInputStream(url);
        String imgName = saveImageToDisk(inputStream, savePath);
        return imgName;
    }

    /**
     * <p>功能描述: [自动创建多层目录] </p>
     * @Title mkdirs
     * @param destPath
     */
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        // 当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    public static void mkdirs( File file ) {
        // 当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }


    /**
     * 解决下载文件名称乱码
     * @param filename
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String formatFileName(String filename, HttpServletRequest request)
        throws UnsupportedEncodingException {
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
            // win10 ie edge 浏览器 和其他系统的ie
            filename = URLEncoder.encode(filename, "UTF-8");
        } else {
            // fe
            filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
        }
        return filename;
    }

    /**
     * 判断文件编码格式
     * @param path
     * @return
     */
    public static String getFileEncodeUTFGBK(String path) {
        String enc = Charset.forName("GBK").name();
        File file = new File(path);
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] b = new byte[3];
            in.read(b);
            in.close();
            if (b[0] == -17 && b[1] == -69 && b[2] == -65) {
                enc = Charset.forName("UTF-8").name();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // System.out.println("文件编码格式为:" + enc);
        return enc;
    }

    /**
     * 从url中剥离出文件名
     * @param url
     *      格式如：http://keking.ufile.ucloud.com.cn/20171113164107_月度绩效表模板(新).xls?UCloudPublicKey=ucloudtangshd@weifenf.com14355492830001993909323&Expires=&Signature=I D1NOFtAJSPT16E6imv6JWuq0k=
     * @return
     */
    public static String getFileNameFromURL(String url) {
        // 因为url的参数中可能会存在/的情况，所以直接url.lastIndexOf("/")会有问题
        // 所以先从？处将url截断，然后运用url.lastIndexOf("/")获取文件名
        String noQueryUrl = url.substring(0, url.indexOf("?") != -1 ? url.indexOf("?") : url.length());
        String fileName = noQueryUrl.substring(noQueryUrl.lastIndexOf("/") + 1);
        return fileName;
    }

    /**
     * 获取文件后缀
     * @param fileName
     * @return
     */
    public static String getSuffixFromFileName(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        return suffix;
    }
}
